<script setup lang="ts">
import { ref, onMounted, computed, reactive, UnwrapRef } from 'vue'
import { useRoute, useRouter } from "vue-router";
import { teachLiveLast, teachLiveList, teachLiveSecret, teachLiveFinish } from '../stores/api/live'
import { useCounterStore } from '../stores/counter'
import { useWebSocket } from '../stores/websocket'
import startLive from './startLive.vue'
import { ImgUrlPrefix } from '../utils/config'
import type { TableProps } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import dayjs from "dayjs";
const store = useCounterStore()
const {
  clearMessages
} = useWebSocket()
const router:any = useRouter()
const tabList = ref([
    {name: '全部', id: 1},
    {name: '直播', id: 2}
])
const info:any = ref({})
const isShow:any = ref(false) // 是否显示弹窗
const loading = ref(false)
const isShowLiveInfo = ref<Boolean>(false) // 进入直播弹窗
const secret_name = ref<object>({}) // 获取直播密钥
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 15,
});
const columns = [
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
  },
  {
    title: '权限',
    dataIndex: 'permission',
    key: 'permission',
  },
  {
    title: '封面图',
    dataIndex: 'thumbnail',
    key: 'thumbnail',
  },
  {
    title: '开始时间',
    dataIndex: 'start_time',
    key: 'start_time',
  },
  {
    title: '结束时间',
    dataIndex: 'end_time',
    key: 'end_time',
  },
  {
    title: '进入直播间人数',
    dataIndex: 'enter_count',
    key: 'enter_count',
  },
  {
    title: '消息数量',
    dataIndex: 'message_count',
    key: 'message_count',
  },
//   {
//     title: '直播流地址',
//     dataIndex: 'stream',
//     key: 'stream',
//   }
//   {
//     title: '操作',
//     key: 'action',
//   },
];

const data_list = ref([
  {
    key: '1',
    name: 'John Brown',
    age: 32,
    address: 'New York No. 1 Lake Park',
    tags: ['nice', 'developer'],
  },
  {
    key: '2',
    name: 'Jim Green',
    age: 42,
    address: 'London No. 1 Lake Park',
    tags: ['loser'],
  },
  {
    key: '3',
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
    tags: ['cool', 'teacher'],
  },
])

interface FormState {
  title: string;
}
const formState: UnwrapRef<FormState> = reactive({
  title: '',
});
const isShowAirtime = ref<Boolean>(true)

// const goCreateLive = (id: any) => {
//     router.push({path: '/courseDetails', query: { id }})
// }
// 上一次直播信息
const lastLiveInfo = () => {
    teachLiveLast({}, 'post').then((res: any) => {
        console.log(res)
        if (res.code == 200) {
            info.value = res.data
        }
    }).catch((err: any) => {
        console.log(err)
    })
}
const status_at = computed(() => {
    if(info.value.status_at) {
        let timestamp = info.value.status_at * 1000
        // console.log(dayjs(timestamp).add(45, 'minute').format('YYYY-MM-DD HH:mm:ss'), dayjs().format('YYYY-MM-DD HH:mm:ss'))
        //  计算距离时间45分钟后的时间戳（毫秒）- 当前时间戳（毫秒）
        return dayjs(timestamp).add(45, 'minute').valueOf() - dayjs().valueOf()
    } else {
        return -1
    }
    
})
// 直播记录
const getList = () => {
    loading.value = true
    teachLiveList({ page: pagination.current, title: formState.title}, 'post').then((res: any) => {
        console.log(res)
        if (res.code == 200) {
            loading.value = false
            data_list.value = res.data.items
            pagination.total = res.data.total
        }
    }).catch((err: any) => {
        loading.value = false
        console.log(err)
    })
}

const handleTableChange: TableProps['onChange'] = (
  pag: { pageSize: number; current: number }
) => {
  console.log(pag?.current)
  pagination.current = pag?.current
  getList()
};
// 去开播
const goLive = () => {
   router.push({path: '/live', query: { isGain: true}})
}
// 去创建直播
const goCreateLive = () => {
    // router.push({path: '/createLive', query: { isGain: true}})
    isShow.value = true
    clearMessages() // 创建直播清空消息列表
}

// 获取直播密钥
const handleLiveSecret = () => {
    isShowLiveInfo.value = true
    teachLiveSecret({ }, 'post').then((res: any) => {
        console.log(res)
        if (res.code == 200) {
           secret_name.value = res.data
        }
    }).catch((err: any) => {
        console.log(err)
    })
}

// 结束直播
const handleLiveFinish = () => {
    teachLiveFinish({}, 'post').then((res: any) => {
        console.log(res)
        if (res.code == 200) {
            message.success(res.message);
            lastLiveInfo()
        }
    }).catch((err: any) => {
        console.log(err)
    })
}

const handleBackChange = (val:any) => {
    isShow.value = val.isShow
    lastLiveInfo() // 重新获取直播信息
}

// 图片地址拼接
const getImgUrl = (val) => {
    const url = ImgUrlPrefix(val)
    return url
}

// 搜索
const onSubmit = () => {
    getList()
}
// 取消
const onCancel = () => {
    formState.title = ''
    getList()
}

// 刷新
const getRefresh = () => {
    getList()
}

const times = computed(() => {
    const date = Date.now();
    if(info.value.status_at && info.value.status_at != 0) {
        let time = info.value.status_at * 1000 - date
        console.log('time', time)
        if(time < 0) {
            return time
        } else {
            return info.value.status_at * 1000
        }
    } else {

        return 0
    }
})

const onFinish = () => {
    console.log('完成')
    isShowAirtime.value = false
}
onMounted(() => {
    lastLiveInfo()
    getList()
})
</script>

<template>
 <div class="live-list">
    <a-card class="top-content-p" title="直播间信息" style="width: 100%">
        <template #extra>
            <div>
                <a-button v-if="info.status == 40" type="primary" class="btn-ss" @click="handleLiveFinish" style="margin-right:10px">结束直播</a-button>
                <a-button v-if="info.status == 10 || info.status == 30" type="primary" class="btn-ss" @click="goLive">进入直播间</a-button>
                <a-button v-else-if="info.status == 20 " type="primary" class="btn-ss" @click="goCreateLive">创建直播</a-button> <!-- || (status_at < 0 && info.status == 40) -->
                <a-button v-else-if="info.status == 40" type="primary" class="btn-ss" @click="handleLiveSecret">获取直播密钥</a-button>  <!-- && status_at > 0 -->
            </div>
        </template>
        <div class="box-flex">
            <div class="content-box">
                <div class="name-item">直播标题：<span class="content-ssv">{{info.title}}</span></div>
                <div class="name-item">
                    状态：
                    <span>
                        <a-tag color="green" v-if="info.status == 10">直播中</a-tag>
                        <a-tag color="blue" v-else-if="info.status == 20">未直播</a-tag>
                        <a-tag color="purple" v-else-if="info.status == 30">直播中断</a-tag>
                        <a-tag color="cyan" v-else-if="info.status == 40">直播预告</a-tag>
                        <span v-else>--</span>
                    </span>
                </div>
                <div class="name-item">
                    权限：
                    <span>
                        <a-tag color="green" v-if="info.permission == 10">所有人</a-tag>
                        <a-tag color="cyan" v-else-if="info.permission == 20">会员</a-tag>
                        <span v-else>--</span>
                    </span>
                </div>
                <div class="name-item">封面图：<span class="content-ssv"><a-image :width="80" :src="getImgUrl(info.thumbnail)" class="thumbnail_"/></span></div>
                <div class="name-item" style="display: flex;" v-if="info.status == 40">
                    直播预告：
                    <div v-if="times > 0 && isShowAirtime">
                        <a-statistic-countdown :value="times" style="margin-right: 50px" @finish="onFinish" :style="{'margin-right': 0}" :valueStyle="{color: '#f50','marginRight': 0, fontSize:'20px'}">
                        </a-statistic-countdown>
                    </div>
                    <span class="content-ssv" v-else>{{store.timestampChangDate(info.status_at * 1000)}}</span>
                </div>
                <div class="name-item">时间：<span class="content-ssv">{{store.timestampChangDate(info.last_time * 1000)}}</span></div>
            </div>
        </div>
    </a-card>
     <div class="list-box">
        <div class="form-filter">
            <a-form layout="inline" :model="formState" >
                <a-form-item label="标题">
                    <a-input v-model:value="formState.title" placeholder="请输入标题" />
                </a-form-item>
                <a-form-item>
                    <a-button type="primary" class="btn-ss" @click="onSubmit">搜 索</a-button>
                    <a-button style="margin: 0 20px;" @click="onCancel">取 消</a-button>
                    <a-button type="primary" class="btn-ss" @click="getRefresh">刷新</a-button>
                </a-form-item>
            </a-form>
            
        </div>
        <a-table :columns="columns" :pagination="pagination"
        :loading="loading" :data-source="data_list" @change="handleTableChange">
            <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'teacher_id'">
                    <span>
                       {{ record.teacher_id }}
                    </span>
                </template>
                <template v-if="column.key === 'title'">
                    <span>
                       {{ record.title }}
                    </span>
                </template>
                <template v-else-if="column.key === 'permission'">
                    <span>
                        <a-tag color="green" v-if="record.permission == 10">所有人</a-tag>
                        <a-tag color="cyan" v-else-if="record.permission == 20">会员</a-tag>
                        <span v-else>--</span>
                    </span>
                </template>
                <template v-else-if="column.key === 'thumbnail'">
                    <span>
                        <img :src="getImgUrl(record.thumbnail)" alt="" class="thumbnail_">
                    </span>
                </template>
                <template v-if="column.key === 'start_time'">
                    <span>
                       {{ store.timestampChangDate(record.start_time * 1000) }}
                    </span>
                </template>
                <template v-if="column.key === 'end_time'">
                    <span>
                       {{ store.timestampChangDate(record.end_time * 1000) }}
                    </span>
                </template>
                <template v-if="column.key === 'enter_count'">
                    <span>
                       {{ record.enter_count }}
                    </span>
                </template>
                <template v-if="column.key === 'message_count'">
                    <span>
                       {{ record.message_count }}
                    </span>
                </template>
                <template v-if="column.key === 'stream'">
                    <span>
                       {{ record.stream }}
                    </span>
                </template>
                <!-- <template v-else-if="column.key === 'action'">
                    <span>
                    <a  @click="goCreateLive(record.id)">详情</a>
                    </span>
                </template> -->
            </template>
        </a-table>
     </div>
     <start-live :isShow="isShow" :info="info" @backChange="handleBackChange" :secret_name="secret_name"></start-live>
 </div>
</template>

<style scoped>
.live-list{
    padding: 15px;
}
.top-content-p{
     background-color: #fff;
    /*padding: 10px 15px;
    border-radius: 6px; */
}
.title-item-p{
    line-height: 40px;
    font-weight: bold;
    font-size: 16px;
}
.box-flex{
    display: flex;
    align-items: center;
}
.content-box{
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    margin: 6px 0;
}
.btn-ss{
    background-color: #fe5d26;
    height: 32px;
}
.btn-ss:hover{
    background-color: #fe5d26;
}
.name-item{
    line-height: 36px;
    min-width: 200px;
    color: #333;
    margin-right: 50px;
}
.name-item span{
    margin-left:4px;
}
.content-ssv{
    color: #000;
    margin-left:4px;
}
.thumbnail_{
    width: 80px;
    height: 80px;
    object-fit: cover;
}
.tab-box{
    display: flex;
    list-style: none;
    padding: 0;
}
.tab-item{
    margin-right: 10px;
    background-color: rgba(37,38,50,1);
    border: 1px solid rgba(37,38,50,1);
    padding: 8px 15px;
    border-radius: 16px;
}
.list-box{
    /* display: grid; */
    /* grid-template-columns: 1fr 1fr 1fr 1fr 1fr; */
    /* grid-template-rows: 200px 200px; */
    /* grid-gap: 20px; */
    /* display: flex;
    flex-wrap: wrap; */
    margin-top: 15px;
}

.form-filter{
   margin: 20px 0;   
   display: flex;
   justify-content: flex-end;
}
.list-item{
    font-size: 16px;
    width: 50%;
    margin-right: 20px;
    margin-bottom: 15px;
}
@media (min-width: 884px) {
    .list-item {
        width: 31.3%;
    }
}
@media (min-width: 1140px) {
    .list-item {
        width: 23%;
    }
}
@media (min-width: 1596px) {
    .list-item {
        width: 18%;
    }
}
.item-name-s{
    font-size: 14px;
    margin-top: 20px;
    color: rgba(255,255,255,0.75);
}
.item-cover-img{
    width: 100%;
    height: 150px;
    margin-bottom: 12px;
}
.item-cover-img img{
    width: 100%;
    height: 100%;
    border-radius: 6px;
}
</style>